﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace UDPRelayControl
{
	public class UDPControlManager : DispatcherObject
	{
		UdpClient udpClient;
		IPEndPoint RemoteIpEndPoint;
		public event EventHandler<OnReceivedMessageEventArgs> OnReceivedMessage;

		public UDPControlManager() { }

		public UDPControlManager(string aServerIP, int aServerPort)
		{
			udpClient = new UdpClient(aServerPort);
			RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, aServerPort);

			ConnectToAServer(aServerIP, aServerPort);

			Task receivingMessageTask = new Task(new Action(ReceiveMessage));
			receivingMessageTask.Start();
		}

		public void SendCommand(string command)
		{
			try
			{
				Byte[] sendBytes = Encoding.ASCII.GetBytes(command);
				udpClient.Send(sendBytes, sendBytes.Length);
			}
			catch (Exception e)
			{
				Console.WriteLine(e.Message);
			}
		}

		private void ConnectToAServer(string aServerIP, int aServerPort)
		{
			udpClient.Connect(aServerIP, aServerPort);
		}


		private void ReceiveMessage()
		{
			while (true)
			{
				Thread.Sleep(300);
				try
				{
					Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
					string returnData = Encoding.ASCII.GetString(receiveBytes);

					this.Dispatcher.BeginInvoke(new Action<object, OnReceivedMessageEventArgs>(OnReceivedMessage), this, new OnReceivedMessageEventArgs(returnData));

					
				}
				catch (Exception e)
				{
					Console.WriteLine(e.Message);
				}
			}
		}
	}
}
